import { Redirect, Route, Switch } from "react-router-dom";
import { useState } from 'react';
import { getStore } from "../utils/localStore";
import { commonUtils } from "../utils/utils";


export class IRouteViewProps {
  title?: string;  // 标题
  path?: string;     // 路径
  redirect?: string;  // 重定向
  component?: any;
  isAuth?: boolean = true; // 是否需要认证  默认是true
  exact?: boolean = false;  // 路由是否强匹配  默认是false
  children?: IRouteViewProps[];
}


const RouteView = (props: IRouteViewProps) => {



  const [isLogin] = useState(getStore(commonUtils.accessToken) != null ? true : false);




  return (
    <Switch>
      {props.children &&
        props.children.map((item, index) => {
          if (item.redirect) {
            return (
              <Redirect
                key={index}
                from={item.path}
                to={item.redirect}
              ></Redirect>
            );
          }
          return (

            (item.isAuth === false || isLogin) ?
              <Route
                key={index}
                path={item.path}
                exact={item.exact}
                render={(props) => {
                  return (
                    item.component && (
                      <item.component
                        children={item.children}
                        {...props}
                      ></item.component>
                    )
                  );
                }}
              ></Route>

              : <Redirect to='/login' />
          )
        })}

    </Switch>
  );
};

export default RouteView;
